package org.jeecg.modules.caiGgl.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.caiGgl.DetailTablePolicy;
import org.jeecg.modules.caiGgl.entity.HqCggl;
import org.jeecg.modules.caiGgl.service.IHqCgglService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gudingzichan.entity.Gudingzichan;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 采购管理
 * @Author: jeecg-boot
 * @Date: 2020-06-17
 * @Version: V1.0
 */
@Api(tags = "采购管理")
@RestController
@RequestMapping("/caiGgl/hqCggl")
@Slf4j
public class HqCgglController extends JeecgController<HqCggl, IHqCgglService> {
    @Autowired
    ISysDepartService sysDepartService;
    @Autowired
    DetailTablePolicy detailTablePolicy;

    @Autowired
    private IHqCgglService hqCgglService;
    @Autowired
    ISysCategoryService sysCategoryService;

    // 大屏数据
    @GetMapping(value = "/dapsu_caigzxl")
    public Result<?> dapsu_caigzxl(String startDate, String endDate) {
        List<Map<String, Object>> list = hqCgglService.jisCaigzxl(startDate, endDate);
        return Result.ok(list);
    }

    @AutoLog(value = "ag_leave-任务审批")
    @ApiOperation(value = "ag_leave-任务审批", notes = "ag_leave-任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody Map params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        hqCgglService.complateTask(loginUser, (String) params.get("taskId"), (String) params.get("processInstanceId"),
                (Integer) params.get("auditStatus"), (String) params.get("auditMemo"), (String) params.get("auditUser"));

        return Result.ok("操作成功");
    }

    @RequestMapping(value = "/exportWord")
    public ModelAndView exportWord(HttpServletRequest request, HttpServletResponse response, HqCggl hqCggl) throws Exception {
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            //获取数据集合
            List<HqCggl> list = new ArrayList<>();
            for (String id : selectionList) {
                HqCggl hqCggl1 = hqCgglService.getById(id);
                if (hqCggl1 != null)
                    list.add(hqCggl1);
            }

            Map<String, Object> map_docx = new HashMap<>();
            map_docx.put("{{1_1}}", 0);
            map_docx.put("{{1_2}}", 0);
            map_docx.put("{{1_3}}", 0);
            map_docx.put("{{1_4}}", 0);
            map_docx.put("{{1_5}}", 0);
            map_docx.put("{{1_6}}", 0);
            map_docx.put("{{1_count}}", 0);
            map_docx.put("{{2_1}}", 0);
            map_docx.put("{{2_2}}", 0);
            map_docx.put("{{2_3}}", 0);
            map_docx.put("{{2_4}}", 0);
            map_docx.put("{{2_5}}", 0);
            map_docx.put("{{2_6}}", 0);
            map_docx.put("{{2_count}}", 0);
            map_docx.put("{{3_1}}", 0);
            map_docx.put("{{3_2}}", 0);
            map_docx.put("{{3_3}}", 0);
            map_docx.put("{{3_4}}", 0);
            map_docx.put("{{3_5}}", 0);
            map_docx.put("{{3_6}}", 0);
            map_docx.put("{{3_count}}", 0);

            //遍历数据，按照类型排序，再对应采购方式求出每项合计
            Map<String, List<HqCggl>> result = list.parallelStream().collect(Collectors.groupingBy(HqCggl::getType));
            result.forEach((k, v) -> {
                System.out.println(k);
                // 公开招标
                Map<String, Long> result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("1")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_1", result2.get("1") == null ? 0 : result2.get("1"));

                // 邀请招标
                result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("2")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_2", result2.get("2") == null ? 0 : result2.get("2"));

                // 竞争性谈判
                result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("3")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_3", result2.get("3") == null ? 0 : result2.get("3"));

                // 询价
                result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("4")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_4", result2.get("4") == null ? 0 : result2.get("4"));

                // 单一来源
                result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("5")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_5", result2.get("5") == null ? 0 : result2.get("5"));

                // 网上竞价
                result2 = v.parallelStream().filter(p -> p.getCaigfs().equals("6")).collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.counting()));
                map_docx.put(k + "_6", result2.get("6") == null ? 0 : result2.get("6"));
            });

            Map<String, Long> typeCounting = list.parallelStream().collect(Collectors.groupingBy(HqCggl::getType, Collectors.counting()));
            map_docx.put("1_count", typeCounting.get("1"));
            map_docx.put("2_count", typeCounting.get("2"));
            map_docx.put("3_count", typeCounting.get("3"));

            Map<String, DoubleSummaryStatistics> caigFsSum = list.parallelStream().collect(Collectors.groupingBy(HqCggl::getCaigfs, Collectors.summarizingDouble(HqCggl::getYusje)));
            map_docx.put("1_sum", caigFsSum.get("1") == null ? 0 : caigFsSum.get("1").getSum());
            map_docx.put("2_sum", caigFsSum.get("2") == null ? 0 : caigFsSum.get("2").getSum());
            map_docx.put("3_sum", caigFsSum.get("3") == null ? 0 : caigFsSum.get("3").getSum());
            map_docx.put("4_sum", caigFsSum.get("4") == null ? 0 : caigFsSum.get("4").getSum());
            map_docx.put("5_sum", caigFsSum.get("5") == null ? 0 : caigFsSum.get("5").getSum());
            map_docx.put("6_sum", caigFsSum.get("6") == null ? 0 : caigFsSum.get("6").getSum());

            // id分组统计
            Map<String, DoubleSummaryStatistics> xiangmhj = list.parallelStream().collect(Collectors.groupingBy(HqCggl::getId, Collectors.summarizingDouble(HqCggl::getYusje)));
            AtomicReference<Double> xiangmhjje = new AtomicReference<>((double) 0);
            AtomicLong xiangmhjsl = new AtomicLong();

            xiangmhj.forEach((k, v) -> {
                xiangmhjje.updateAndGet(v1 -> new Double((double) (v1 + v.getSum())));
                xiangmhjsl.addAndGet(v.getCount());
            });
            map_docx.put("xiangmhjje", xiangmhjje.get());
            map_docx.put("xiangmhjsl", xiangmhjsl.get());

            // 按需求单位分组统计
            AtomicLong xqdw_xmshj = new AtomicLong(0);
            AtomicReference<Double> xqdw_jehj = new AtomicReference<>((double) 0);

            Map<String, DoubleSummaryStatistics> xuqdw = list.parallelStream().collect(Collectors.groupingBy(HqCggl::getXuqdw, Collectors.summarizingDouble(HqCggl::getYusje)));
            AtomicInteger index = new AtomicInteger(0);
            xuqdw.forEach((k, v) -> {
                SysDepart sysDepart = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("org_code", k), false);
                if(sysDepart != null)
                    map_docx.put("xqdw_" + index + "_departName", sysDepart.getDepartName());

                map_docx.put("xqdw_" + index + "_count", v.getCount());
                xqdw_xmshj.updateAndGet(v1 -> v1 + v.getCount());

                map_docx.put("xqdw_" + index + "_sum", v.getSum());
                xqdw_jehj.updateAndGet(v1 -> v1 + v.getSum());

                index.getAndIncrement();
            });

            map_docx.put("xqdw_xmshj", xqdw_xmshj);
            map_docx.put("xqdw_jehj", xqdw_jehj);

            List<HqCggl> listHqCgglWZ = new ArrayList<>();
            // 物资类详情列表
            List<HqCggl> list4Wuz = list.parallelStream().filter(f->f.getType().equals("1")).collect(Collectors.toList());
            list4Wuz.forEach(e->{
                String baozqd = e.getBaozqd();
                String yuskm = e.getYuskm();
                if(baozqd!=null){
                    SysDepart byIdSysDepart = sysDepartService.getById(baozqd);
                    String departName = byIdSysDepart.getDepartName();
                    e.setBaozqd(departName);
                }
                if (yuskm!=null){
                    SysCategory byIdSysCategory = sysCategoryService.getById(yuskm);
                    String name = byIdSysCategory.getName();
                    e.setYuskm(name);
                }
                listHqCgglWZ.add(e);
            });
            map_docx.put("list4Wuz", listHqCgglWZ);
            map_docx.put("wuz_hjje", listHqCgglWZ.stream().collect(Collectors.summarizingDouble(sum->sum.getYusje())).getSum());

            // 工程类详情列表
            List<HqCggl> listHqCgglGC = new ArrayList<>();
            List<HqCggl> list4Gongc = list.parallelStream().filter(f->f.getType().equals("2")).collect(Collectors.toList());
            list4Gongc.forEach(e->{
                String baozqd = e.getBaozqd();
                String yuskm = e.getYuskm();
                if(baozqd!=null){
                    SysDepart byIdSysDepart = sysDepartService.getById(baozqd);
                    String departName = byIdSysDepart.getDepartName();
                    e.setBaozqd(departName);
                }
                if (yuskm!=null){
                    SysCategory byIdSysCategory = sysCategoryService.getById(yuskm);
                    String name = byIdSysCategory.getName();
                    e.setYuskm(name);
                }
                listHqCgglGC.add(e);
            });
            map_docx.put("list4Gongc", listHqCgglGC);
            map_docx.put("gongc_hjje", listHqCgglGC.stream().collect(Collectors.summarizingDouble(sum->sum.getYusje())).getSum());

            // 服务类详情列表
            List<HqCggl> listHqCgglFW = new ArrayList<>();
            List<HqCggl> list4Fuw = list.parallelStream().filter(f->f.getType().equals("3")).collect(Collectors.toList());
            list4Fuw.forEach(e->{
                String baozqd = e.getBaozqd();
                String yuskm = e.getYuskm();
                if(baozqd!=null){
                    SysDepart byIdSysDepart = sysDepartService.getById(baozqd);
                    String departName = byIdSysDepart.getDepartName();
                    e.setBaozqd(departName);
                }
                if (yuskm!=null){
                    SysCategory byIdSysCategory = sysCategoryService.getById(yuskm);
                    String name = byIdSysCategory.getName();
                    e.setYuskm(name);
                }
                listHqCgglFW.add(e);
            });
            map_docx.put("list4Fuw", listHqCgglFW);
            map_docx.put("fuw_hjje", listHqCgglFW.stream().collect(Collectors.summarizingDouble(sum->sum.getYusje())).getSum());


            //导出Word
            Configure config = Configure.newBuilder()
                    .bind("list4Wuz", detailTablePolicy)
                    .bind("list4Gongc", detailTablePolicy)
                    .bind("list4Fuw", detailTablePolicy)
                    .build();

            XWPFTemplate template = XWPFTemplate.compile("d:\\采购模板.docx", config).render(map_docx);
            template.write(response.getOutputStream());
        }

        return null;
    }

    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(HqCggl hqCggl,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {

        Page<HqCggl> page = new Page<HqCggl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqCggl> iPage = hqCgglService.myApplyList(page, user, hqCggl);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
                if(record.getTaskName()==null&&record.getAssignName()==null){
                    record.setTaskName("流程已结束");
                    record.setAssignName("流程已结束");
                }
            });
        }
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(HqCggl hqCggl,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqCggl> page = new Page<HqCggl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqCggl> iPage = hqCgglService.myTodoTasks(page, user, hqCggl);
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(HqCggl hqCggl,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqCggl> page = new Page<HqCggl>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqCggl> iPage = hqCgglService.myDoneTasks(page, user, hqCggl);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                }
            });
        }
        return Result.ok(page);
    }

    /**
     * 分页列表查询
     *
     * @param hqCggl
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "采购管理-分页列表查询")
    @ApiOperation(value = "采购管理-分页列表查询", notes = "采购管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HqCggl hqCggl,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HqCggl> queryWrapper = QueryGenerator.initQueryWrapper(hqCggl, req.getParameterMap());
        Page<HqCggl> page = new Page<HqCggl>(pageNo, pageSize);
        IPage<HqCggl> pageList = hqCgglService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param hqCggl
     * @return
     */
    @AutoLog(value = "采购管理-添加")
    @ApiOperation(value = "采购管理-添加", notes = "采购管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HqCggl hqCggl) {
        hqCgglService.save(hqCggl);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqCgglService.startFlow(hqCggl, loginUser);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hqCggl
     * @return
     */
    @AutoLog(value = "采购管理-编辑")
    @ApiOperation(value = "采购管理-编辑", notes = "采购管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HqCggl hqCggl) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqCgglService.updateById(hqCggl);
        hqCgglService.applyAgain(hqCggl, user);

        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购管理-通过id删除")
    @ApiOperation(value = "采购管理-通过id删除", notes = "采购管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hqCgglService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "采购管理-批量删除")
    @ApiOperation(value = "采购管理-批量删除", notes = "采购管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hqCgglService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购管理-通过id查询")
    @ApiOperation(value = "采购管理-通过id查询", notes = "采购管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HqCggl hqCggl = hqCgglService.getById(id);
        if (hqCggl == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(hqCggl);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hqCggl
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqCggl hqCggl) {
        return super.exportXls(request, hqCggl, HqCggl.class, "采购管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HqCggl.class);
    }

}
